package com.kdtech.analyse.news;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.crawler.CrawlHTML;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.RegexUtils;
import com.kdtech.utils.StringUtils;
import com.kdtech.utils.HtmlCleaner;

/**
 *	5982
 * http://www.jwb.com.cn/  今晚网
 * 	
 * @author KK
 *
 */
public class JwbNewsAnalyse implements AnalyseNews {
	
	private static final String[] regex={	
		
		"http://www.jwb.com.cn/[a-z0-9\\/]+/t[0-9\\_]+.html",
		"http://news.jwb.com.cn/art/[0-9\\/]+/art[0-9\\_]+.html"
	};	
	
	
	public boolean isDetailPage(String url) {
		return RegexUtils.matchAnyIgnoreCase(url, regex);
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		if (urlMeta.getHtml() == null) {
		}	
		NewsMeta news=new NewsMeta();
		String htmltxt=urlMeta.getHtml();
		String url=urlMeta.getUrl();
		if(!isDetailPage(url)){
		}
		String title=null;
		String content=null;
		String author=null;
		Long date=null;
		Document doc=Jsoup.parse(htmltxt);				
		news.setUrl(url);	
		
		title=doc.select("div#title").text();
		if(StringUtils.isBlank(title)){
			title =doc.select("title").text();
			title =StringUtils.substringBefore(title, "-");
		}
		content=HtmlCleaner.getContentHtml(url,doc.select("div#news_content"));	
		if(StringUtils.isBlank(content)){
			content=HtmlCleaner.getContentHtml(url,doc.select("div#zoom"));	
			if(StringUtils.isBlank(content)){
				content=HtmlCleaner.getContentHtml(url,doc.select("div.Article"));	
			}
		}
		
		/*
		 * 作者
		 */
		String authorStr=null;
		authorStr=doc.select("div#news_content").text();
		if(StringUtils.isBlank(authorStr)){
			authorStr=doc.select("div.Article").text();
			if(StringUtils.isBlank(authorStr)){
				authorStr=doc.select("div#riqi").text();
			}
		}
		author=StringUtils.substringBetween(authorStr, "来源："," ");
		if(StringUtils.isBlank(author)){
			author=StringUtils.substringBetween(authorStr, "来源:", " ");
		}
	
		date=DateUtils.matchDate(doc.select("div#riqi").text());
		if(date==null){
			date=DateUtils.matchDate(url);
		}
		if (StringUtils.isNotBlank(title) && date!=null){			
			news.setTitle(StringUtils.trimSpace(title));
			news.setContent(content);
			news.setAuthor(author);
			news.setDate(date);	
			news.setType(1);	
		}
		return news;
	}	
	public static void main(String[] args) {
		String url="http://news.jwb.com.cn/art/2015/10/16/art_179_5907255.html";
		JwbNewsAnalyse analyse=new JwbNewsAnalyse();		
		System.out.println(analyse.isDetailPage(url));
		UrlMeta meta=CrawlHTML.responseToURL(url);
		System.out.println(analyse.parserHtml(meta));
	}

	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}

	
	public boolean isNeedUpdate(){
		return false;
	}
}
